<template>
  <div class="searchContainer">
    <!--    //搜索-->
    <van-sticky class="search">
      <SearchBox 
          :isDisabled="false" 
          :haveLogo="false"
          haveCancel
          v-model.trim="keyword"
          @focus="handleFocus"
          @search="handleSearch"
          @cancel="handleCancel"
          @clear="handleClear"
          @input="handleInput"
          ></SearchBox>
    </van-sticky>
    <!--    历史记录-->
    <div v-show="isShowSearchHistory" class="hotWordsWrap">
      <h2 class="hot_title">历史记录
        <van-icon @click="cleanHistory" name="delete-o" class="delete-o"/>
      </h2>
      <ul class="hotWords">
        <li
            class="word"
            @click="toShowGoods(word)"
            v-for="(word,index) in searchHistory"
            :key="index">{{ word }}
        </li>
      </ul>
    </div>
<!-- 


  div.addEventListener('click', f1)
  div.addEventListener('click', f2)
 -->
    <!-- 热门搜索 -->
    <div v-show="status===1" class="hotWordsWrap">
      <h2 class="hot_title">热门搜索</h2>
      <ul class="hotWords">
        <li
            @click="toShowGoods(word.keyword)"
            :class="{hot_light:word.highlight}"
            class="word"
            v-for="(word,index) in hotKeywordsList"
            :key="index">{{ word.keyword }}
        </li>
      </ul>
    </div>

    <!-- 搜索实时推荐 -->
    <ul class="real_time_recommend" v-show="status===2">
      <li @click="showGoodList(item)"
          class="recommend_item"
          v-for="(item,index) in searchTipsList"
          :key="index">
        <p class="item_text">{{ item }}</p>
        <van-icon name="arrow" class="arrow"/>
      </li>
    </ul>

    <!-- 商品列表 -->
    <ShowGoods v-if="status===3"></ShowGoods>
  </div>
</template>

<script>
import {mapState} from 'vuex';
import debounce from 'lodash/debounce'
import ShowGoods from "@/pages/Search/ShowGoods/ShowGoods";

export default {
  name: "Search",
  components: {ShowGoods},
  data() {
    return {
      searchHistory: [],//搜索历史
      keyword: '',
      executeOnce:true, //用于监视数据中,强制刷新的时候，让路由不回到首页，停在类似/home/15661321的当前页面，
      status: 1, // 1: 搜索页面 2：关键字列表页面 3：商品列表界面
    }
  },
  computed: {
    ...mapState({
      searchInfo: state => state.search.searchInfo,//初始化数据
      searchTipsList: state => state.search.searchTipsList,//搜索实时推荐列表
      goodsInfo: state => state.search.goodsInfo,
    }),

    //获取搜索热词
    hotKeywordList() {
      return this.searchInfo.hotKeywordVOList || []
    },

    // 是否展示搜索历史
    isShowSearchHistory() {
      return (this.searchHistory.length && this.status===1)
    },

  },

  mounted() {
    this.$store.dispatch('getSearchInfo')
    const searchHistory = JSON.parse(localStorage.getItem('searchHistory_key')) || []
    this.searchHistory = searchHistory
  },

  methods: {
    /* 
    点击清除
    */
    handleClear () {
      console.log('clear')
      this.showHistory()
    },

    /* 
    点击取消
    */
    handleCancel () {
      console.log('cancel')
      this.$store.commit('REMOVE_SEARCH_TIPS_LIST')
      this.$store.commit('REMOVE_SEARCH_GOODS_INFO')
      this.$router.replace('/home')
    },

    /* 
    输入发生改变
    */
    handleInput () {
      if (this.keyword) {
        this.showWordList()
      } else {
        this.showHistory()
      }
    },

    /* 
    处理搜索
    */
    handleSearch (value) {
      console.log('search')
      this.showGoodList(value)
    },

    /* 
    处理获得焦点
    */
    handleFocus () {
      console.log('focus')
      if (this.keyword && this.status!=2) {
        this.showWordList()
      }
    },
    /* 
    显示关键字列表
    */
    showWordList: debounce(function () {
        const {keyword} = this
        this.status = 2
        this.$store.dispatch('getSearchTipsList', {keywordPrefix: keyword})
      }, 200),

    /* 
    显示历史记录界面
    */
    showHistory () {
      this.status = 1
      this.keyword = ''
      this.$store.commit('REMOVE_SEARCH_TIPS_LIST')
      this.$store.commit('REMOVE_SEARCH_GOODS_INFO')
    },

    /* 
    展示搜索到的商品
     */
    showGoodList(keyword) {
      console.log(keyword)
      //改变搜索框显示的文字
      this.keyword = keyword
      //保存搜索历史记录 这块
      this.saveHistory(keyword)
      //展示商品
      this.status = 3
      // 清空搜索列表 用于关闭展示搜索提示
      this.$store.commit('REMOVE_SEARCH_TIPS_LIST')
      //清空上一次搜索到的商品列表
      this.$store.commit('REMOVE_SEARCH_GOODS_INFO')
      this.$router.replace({
        path: '/search',
        query: {
          keyword
        }
      })
    },

    /* 
    保存搜索关键字道理是记录
    */
    saveHistory(keyword){
      //判断数组中是否已经存在这个历史记录了
      const index = this.searchHistory.findIndex(item => item === keyword)
      // console.log(index)
      if (index !== -1) {
        // 不等于-1说明 有这个历史记录
        this.searchHistory.splice(index, 1)
        this.searchHistory.unshift(keyword)

      } else {
        // 这里是没有这个历史记录
        this.searchHistory.unshift(keyword)
      }
      //保存到本地
      localStorage.setItem('searchHistory_key', JSON.stringify(this.searchHistory))
    },

    /* 
    清空历史搜索记录
     */
    cleanHistory() {
      this.searchHistory = []
      //保存到本地
      localStorage.removeItem('searchHistory_key')
    },

  },

  watch: {
    $route:{
      immediate:true,
      handler(value){
        if (value.fullPath==='/search'){
          this.showHistory()
        } else if(value.fullPath!=='/search') {
          const keyword = value.query.keyword
          this.keyword = keyword
          this.status = 3
          this.$store.dispatch('getSearchShowGoodsInfo', {keyword: keyword})
        }
      }
    },
  },
}
</script>

<style lang="less" scoped>
.searchContainer {
  height: 100%;
  background-color: #EEEEEE;
  // 热搜词，历史搜索
  .hotWordsWrap {
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 15px 15px;
    margin-bottom: 10px;

    .hot_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      align-self: flex-start;
      height: 45px;
      width: 100%;
      font-size: 14px;
      color: #999999;
      line-height: 45px;
      flex: 1;

      .delete-o {
        text-align: center;
        height: 27px;
        width: 27px;
        font-size: 16px;
        line-height: 27px;
        color: #333333;
      }
    }

    .hotWords {
      //background-color:#ffffff;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      width: 100%;
      //justify-content: space-between;
      .word {
        height: 24.5px;
        line-height: 24.5px;
        text-align: center;
        box-sizing: border-box;
        font-size: 12px;
        margin: 0 16px 16px 0;
        padding: 0 7.5px;
        color: #333333;
        border: 1px solid #999;
        border-radius: 4px;

        &.hot_light {
          border-color: #dd1a21;
          color: #dd1a21;
        }
      }
    }
  }

  //  实时推荐列表
  .real_time_recommend {
    width: 375px;
    background-color: #ffffff;
    padding-left: 15px;
    box-sizing: border-box;

    .recommend_item {
      //width: 100%;
      height: 52px;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      border-bottom: 1px solid #d9d9d9;
      color: #333333;
      justify-content: space-between;

      .item_text {
        font-size: 14px;
      }

      .arrow {
        color: #666666;
        font-size: 16px;
        font-weight: bold;
        padding-right: 20px;
      }


    }
  }
}

</style>
